import router, { resetRouter } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Utils from '@utils/index'
import whiteList from '@config/page-white-list' // 不需要登录可访问的页面
import Theme from '@theme'
import variables from '@styles/element-variables.scss'
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = Utils.getPageTitle(to.meta.title)
  const hasToken = Utils.token.get()

  if (hasToken) {
    if (to.path === '/login') { // 已登录跳转到默认页面
      router.push({
        path: '/home'
      })
      NProgress.done()
    } else {
      let theme = Utils.localStorage.get('theme')
      if (!theme) {
        theme = variables.theme
        store.dispatch('settings/themeChangeSetting', variables.theme)
      }
      const thmeObj = new Theme(theme)
      store.dispatch('tagsView/addView', to)
      if (store.getters.menuList.length === 0) {
        const menuList = await store.dispatch('permission/createNewRoutes')

        resetRouter()
        router.addRoutes(menuList)
        const routerPath = Utils.sessionStorage.get('routerPath')

        if (routerPath && routerPath !== '/login') { // 刷新浏览器后回到刷新前的页面
          router.push({ path: routerPath, replace: true })
        } else {
          router.push({
            path: to.path
          })
        }
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 不需要登录可访问
      next()
    } else { // 登录成功后重定向回刚刚访问的页面
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
